package com.oa.mail.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.entity.Tips;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.mail.entity.MailAccount;
import com.oa.mail.entity.MailEmail;
import com.oa.mail.entity.MailEmailVo;
import com.oa.mail.service.MailEmailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月9日
 */
@RestController
@RequestMapping(value = "/*/oa/mail/mailEmail")
@Api(tags = {"邮件表-操作接口"})
public class MailEmailController {

    static Logger logger = LoggerFactory.getLogger(MailEmailController.class);

    @Autowired
    private MailEmailService mailEmailService;

    @ApiOperation(value = "查询单个邮件的全部信息", notes = "条件之间是 and关系,模糊查询写法如 {studentName:'%才哥%'}")
    @ApiResponses({@ApiResponse(code = 200, response = MailEmail.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},pageInfo:{total:总记录数},data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/getMailMessage", method = RequestMethod.GET)
    public Result getMailEmail(@RequestParam Map<String, Object> mailEmail) {
        MailEmailVo mailEmailVo = mailEmailService.getMailEmail(mailEmail);

        return Result.ok().setData(mailEmailVo);
    }


    @ApiOperation(value = "邮件表-查询列表", notes = " ")
    @ApiEntityParams(MailEmail.class)
    @ApiResponses({@ApiResponse(code = 200, response = MailEmail.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listMailEmail(@ApiIgnore @RequestParam Map<String, Object> mailEmail) {
        RequestUtils.transformArray(mailEmail, "ids");
        List<Map<String, Object>> mailEmailList = null;
        QueryWrapper<MailEmail> qw = QueryTools.initQueryWrapper(MailEmail.class, mailEmail);
        IPage page = QueryTools.initPage(mailEmail);
        //如果是为外部邮件系统或者为内部草稿走这逻辑
        if ((!StringUtils.isEmpty(mailEmail.get("type")) && mailEmail.get("type").equals("0")) || (!StringUtils.isEmpty(mailEmail.get("isOuter")) && mailEmail.get("isOuter").equals("1"))) {
            mailEmailList = mailEmailService.selectListMapByWhere(page, qw, mailEmail);    //列出MailEmail列表
        } else if (!StringUtils.isEmpty(mailEmail.get("isAllStar")) && mailEmail.get("isAllStar").equals("1")) { //内部星标走这逻辑
            mailEmailList = mailEmailService.selectListMapByWhere(page, qw, mailEmail);
        } else {
            mailEmailList = mailEmailService.selectListMapByWhere(page, qw, mailEmail);    //剩下的走这条
        }

        return Result.ok("query-ok", "查询成功").setData(mailEmailList).setTotal(page.getTotal());
    }


    @ApiOperation(value = "接收mail_email")
    @ApiResponses({@ApiResponse(code = 200, response = List.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},pageInfo:{total:总记录数},data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/receive", method = RequestMethod.POST)
    public Result receivetMail(@RequestBody MailAccount mailAccount) {
        List<MailEmail> mailEmails = mailEmailService.receivetMail(mailAccount.getEmail());//列出MailEmail列表

        return Result.ok().setData(mailEmails);
    }

    @ApiOperation(value = "接收全部邮箱")
    @ApiResponses({@ApiResponse(code = 200, response = List.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},pageInfo:{total:总记录数},data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/receiveAll", method = RequestMethod.POST)
    public Result receivetMail(@RequestBody List<MailAccount> mailAccounts) {
        List<MailEmail> mailEmails = null;
        if (!mailAccounts.isEmpty()) {
            for (MailAccount mailAccount : mailAccounts) {
                mailEmails = mailEmailService.receivetMail(mailAccount.getEmail());//列出MailEmail列表
            }
        }

        return Result.ok().setData(mailEmails);
    }

    @ApiOperation(value = "邮件表-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = MailEmail.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addMailEmail(@RequestBody MailEmailVo mailEmailVo) {


        Integer num = mailEmailService.save(mailEmailVo);

        return Result.ok("add-ok", "添加成功！").setData(mailEmailVo);
    }

    @ApiOperation(value = "邮件表-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delMailEmail(@RequestBody MailEmail mailEmail) {


        //mailEmailService.deleteByPk(mailEmail);
        Integer num = mailEmailService.removeEmail(mailEmail);

        return Result.ok("del-ok", "删除成功！");
    }

    /***/
    @ApiOperation(value = "将邮件设置为星标", notes = "editMailEmail")
    @ApiResponses({@ApiResponse(code = 200, response = MailEmail.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/setStar", method = RequestMethod.POST)
    public Result editMailEmailStar(@RequestBody MailEmail mailEmail) {


        //mailEmailService.updateByPk(mailEmail);
        Integer num = mailEmailService.setStarMail(mailEmail);

        return Result.ok().setData(mailEmail);
    }

    @ApiOperation(value = "将邮件设置为已读", notes = "setIsReadMailEmail")
    @ApiResponses({@ApiResponse(code = 200, response = MailEmail.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/setRead", method = RequestMethod.POST)
    public Result editMailEmailIsRead(@RequestBody MailEmail mailEmail) {


        mailEmailService.updateByPk(mailEmail);

        return Result.ok().setData(mailEmail);
    }


    @ApiOperation(value = "邮件表-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = MailEmail.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editMailEmail(@RequestBody MailEmailVo mailEmailVo) {


        //mailEmailService.updateByPk(mailEmail);
        mailEmailService.editMailEmail(mailEmailVo);

        return Result.ok("edit-ok", "修改成功！").setData(mailEmailVo);
    }

    @ApiOperation(value = "邮件表-批量修改某些字段", notes = "")
    @ApiEntityParams(value = MailEmail.class, props = {}, remark = "邮件表", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = MailEmail.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        mailEmailService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ApiOperation(value = "邮件表-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelMailEmail(@RequestBody List<MailEmail> mailEmails) {
        User user = LoginUtils.getCurrentUserInfo();
        if (mailEmails.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<MailEmail> datasDb = mailEmailService.listByIds(mailEmails.stream().map(i -> i.getId()).collect(Collectors.toList()));

        List<MailEmail> can = new ArrayList<>();
        List<MailEmail> no = new ArrayList<>();
        for (MailEmail data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            mailEmailService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }

        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ApiOperation(value = "邮件表-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = MailEmail.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(MailEmail mailEmail) {
        MailEmail data = (MailEmail) mailEmailService.getById(mailEmail);
        return Result.ok().setData(data);
    }

}
